<template>
    <!-- 主要内容区域 -->
    <div class="flex-1 p-6 overflow-auto bg-gray-100">
        <div class="bg-white rounded-lg p-6">
            <!-- 搜索区域 -->
            <div class="flex items-center space-x-4 mb-6">
                <el-input v-model="searchForm.keyword" placeholder="请输入部门名称" class="w-64" clearable>
                    <template #prefix>
                        <el-icon>
                            <Search />
                        </el-icon>
                    </template>
                </el-input>
                <el-input v-model="searchForm.username" placeholder="请输入角色" class="w-64" clearable>
                </el-input>
                <el-input v-model="searchForm.phone" placeholder="请输入手机号码" class="w-64" clearable>
                </el-input>
                <el-select v-model="searchForm.status" placeholder="用户状态" class="w-32">
                    <el-option label="全部" value="" />
                    <el-option label="启用" value="1" />
                    <el-option label="禁用" value="0" />
                </el-select>
                <el-button type="primary" class="!rounded-button" @click="handleSearch">
                    <el-icon class="mr-1">
                        <Search />
                    </el-icon>搜索
                </el-button>
                <el-button class="!rounded-button" @click="handleReset">
                    <el-icon class="mr-1">
                        <Refresh />
                    </el-icon>重置
                </el-button>
            </div>
            <!-- 操作按钮 -->
            <div class="flex justify-between mb-4">
                <div class="space-x-2">
                    <el-button type="primary" class="!rounded-button" @click="openDialog('add')">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>新增
                    </el-button>
                    <el-button type="danger" class="!rounded-button whitespace-nowrap" @click="handleDelete">
                        <el-icon class="mr-1">
                            <Delete />
                        </el-icon>删除
                    </el-button>
                    <el-button type="success" class="!rounded-button" @click="handleImport">
                        <el-icon class="mr-1">
                            <Upload />
                        </el-icon>导入
                    </el-button>
                    <el-button type="warning" class="!rounded-button" @click="handleExport">
                        <el-icon class="mr-1">
                            <Download />
                        </el-icon>导出
                    </el-button>
                </div>
            </div>
            <!-- 表格 -->
            <el-table :data="tableData" border stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column label="教师编号" prop="id" width="140" />
        <el-table-column label="教师工号" prop="account" width="140" />
                <el-table-column label="性别" prop="gender" width="80" >
                    <template v-slot="scope">
                        {{ scope.row.gender === 0 ? '男' : '女' }}
                    </template>
                </el-table-column>
        <el-table-column label="学校" prop="school" width="150" />
        <el-table-column label="学院" prop="college" width="150" />
        <el-table-column label="封禁" prop="isDelete" width="120">
          <template #default="scope">
            <el-switch v-model="scope.row.isDelete" />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="120" :formatter="formatDate"/>
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button type="primary" link @click="openDialog('edit', scope.row)">修改</el-button>
            <el-button type="primary" link @click="handleDelete(scope.row)">删除</el-button>
            <el-button type="primary" link @click="handleResetPassword(scope.row)">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增用户' : '编辑用户'" width="500px" destroy-on-close>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="教师工号" prop="account">
            <el-input v-model="form.account" placeholder="请输入教师工号" />
          </el-form-item>
          <el-form-item label="教师姓名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入教师姓名" />
          </el-form-item>
            <el-form-item label="性别" prop="gender">
                <el-select
                        v-model="form.gender"
                        placeholder="请选择性别"
                        style="width: 100%"
                >
                    <el-option label="男" :value="0" />
                    <el-option label="女" :value="1" />
                </el-select>
            </el-form-item>
          <el-form-item label="学校" prop="school">
              <el-input v-model="form.school" placeholder="请输入学校" />
          </el-form-item>
          <el-form-item label="学院" prop="college">
              <el-input v-model="form.college" placeholder="请输入学院" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit(formRef)">确认</el-button>
          </span>
        </template>
      </el-dialog>
            <!-- 分页 -->
            <div class="flex justify-end mt-4">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :total="pagination.total" :page-sizes="[10, 20, 30, 40]"
                    layout="total, sizes, prev, pager, next, jumper" />
            </div>
        </div>
    </div>
    <!-- 上传文件弹窗 -->
    <el-upload ref="upload" :action="uploadUrl" :before-upload="beforeUpload" :on-success="handleUploadSuccess"
        :on-error="handleUploadError" accept=".xls,.xlsx" show-file-list="false" :auto-upload="false">
    </el-upload>
</template>

<script lang="ts" setup>
    import {ref, reactive, onMounted} from "vue";
import * as XLSX from "xlsx";  // 引入 xlsx 库
import { FormInstance, FormRules, ElMessageBox, ElMessage } from "element-plus";
import {getAllTeacher,updateTeacher,addTeacher,deleteTeacher} from "../../api/admin/userManage";
    onMounted(()=>{
        getTeacher(pagination.value)
    })
    async function getTeacher(data) {
        await getAllTeacher(data).then(function (response) {
                tableData.value=response.items[0]
                pagination.value.total=response.total
            }
        )
    }

    
// 日期格式化方法
const formatDate = (row, column, cellValue) => {
    if (!cellValue) return '';
    const d = new Date(cellValue);
    return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`; // 返回 yyyy-mm-dd 格式
};
// 选中的行的ID数组
const selectedRowKeys = ref([]);

const handleSelectionChange = (selection) => {
    selectedRowKeys.value = selection.map(item => item.id);
};

// 重置搜索表单
const handleReset = () => {
  searchForm.value = {
    keyword: "",
    username: "",
    phone: "",
    status: "",
  };
  // 这里可以根据需要重新加载表格数据
};
//搜索栏数据
const searchForm = ref({
    keyword: '',
    username: '',
    phone: '',
    status: '',
    dateRange: [],
});

//表格内容
const tableData = ref([
{
  "id": 1,
  "employeeNumber": "T202301",
  "schoolName": "第一学校",
  "college": "人文学院",
  "createTime":"2021-09-01 14:00"
},{
  "id": 2,
  "employeeNumber": "T202302",
  "schoolName": "第二学校",
  "college": "理工学院"
}
]);

//分页
const pagination = ref({
    currentPage: 1,
    pageSize: 10,
    total: 100
});

// 弹窗相关
const dialogVisible = ref(false);
const dialogType = ref('');
const formRef = ref<FormInstance>();
    const form = ref({
    id: '',
    account: '',
    school: '',
    college: '',
    isDelete:true,
    userName:'',
    createTime: '',
        gender:'',
  });

  const rules = {
    id: [{ required: true, message: '请输入教师编号', trigger: 'blur' }],
    employeeNumber: [{ required: true, message: '请输入教师工号', trigger: 'blur' }],
    schoolName: [{ required: true, message: '请选择学校', trigger: 'change' }],
    college: [{ required: true, message: '请选择学院', trigger: 'change' }],
  };

  const schoolOptions = reactive([
    { id: 1, name: '某某学校' },
    // 其他学校选项...
  ]);
  
  const collegeOptions = reactive([
    { id: 1, name: '工程学院' },
    // 其他学院选项...
  ]);

    //修改与增加教师
    async function add_teacher(data) {
        await addTeacher(data).then(function (response) {
            getTeacher(pagination.value)
        })
    }
    async function update_teacher(data) {
        await updateTeacher(data).then(function (response) {
            getTeacher(pagination.value)
        })
    }

const openDialog = (type: string, row?: any) => {
    dialogType.value = type;
    if (type === 'edit' && row) {
        // 当前行为编辑模式，填充表单数据
        form.value = {
            id: row.id,
            account: row.account,
            userName: row.userName,
            school: row.school,
            college: row.college,
            gender:row.gender
        };
    } else {
        // 清空表单数据
        form.value = {
            id: '',
            account: '',
            userName: '',
            school: '',
            college: '' ,
            gender:'',
        };
    }
    dialogVisible.value = true;
};

//提交
    function handleSubmit (){
        if (dialogType.value === 'add') {
            // 处理添加逻辑
            console.log('提交表单 - 添加', form.value);
            add_teacher(form.value)
            ElMessage.success('添加成功');
        } else if (dialogType.value === 'edit') {
            // 处理修改逻辑
            console.log('提交表单 - 修改', form.value);
            update_teacher(form.value)
            ElMessage.success('修改成功');
        }
        dialogVisible.value = false;
    };

    //删除学生
    async function delete_teacher(data){
        await deleteTeacher(data).then(function (response) {
            getTeacher(pagination.value)
        })
    }
//删除用户
const handleDelete = (row: any) => {
   // 获取当前选中的行
   const selectedRows = tableData.value.filter(row => selectedRowKeys.value.includes(row.id));
    
    if (selectedRows.length === 0) {
        ElMessage.warning('请至少选择一项进行删除');
        return;
    }

    ElMessageBox.confirm(
        '确定要删除选中的用户吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        // 模拟删除操作
        delete_teacher(selectedRows)
        ElMessage.success('删除成功');
    }).catch(() => { });
};


//重置密码
const handleResetPassword = (row: any) => {
    ElMessageBox.confirm(
        '确定要重置该用户的密码吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        console.log('重置密码', row);
        ElMessage.success('密码重置成功');
    }).catch(() => { });
};

// 导入功能
const handleImport = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx, .xls';
    input.onchange = (e: any) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event: any) => {
                const data = event.target.result;
                const wb = XLSX.read(data, { type: 'array' });
                const ws = wb.Sheets[wb.SheetNames[0]];
                const json = XLSX.utils.sheet_to_json(ws, { header: 1 });
                console.log('导入数据:', json);
                // 假设你将数据存入 tableData
                tableData.value = json.slice(1).map((row: any) => {
                    return {
                        id: row[0],
                        username: row[1],
                        nickname: row[2],
                        phone: row[3],
                        account: row[4],
                        address: row[5],
                        status: row[6] === '启用', // 状态转换
                        createTime: row[7]
                    };
                });
                ElMessage.success('文件导入成功');
            };
            reader.readAsArrayBuffer(file);
        }
    };
    input.click();
};

// 导出功能
const handleExport = () => {
    const ws = XLSX.utils.json_to_sheet(tableData.value);  // 将 tableData 转为 sheet
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
    const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' });
    const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
    const url = window.URL.createObjectURL(data);
    const link = document.createElement('a');
    link.href = url;
    link.download = '用户数据.xlsx';  // 设置下载的文件名
    link.click();
    ElMessage.success('文件导出成功');
};
</script>

<style scoped></style>